package com.ruoyi.common.utils.wechat;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONPObject;

import java.util.HashMap;

public class RequestUtils {

    // 获取AccessToken
    public static JSONObject getAccessToken(String appId, String appSecret) {
        String apiUrl = StrUtil.format(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}",
                appId, appSecret
        );
        String body = HttpRequest.get(apiUrl).execute().body();
       /* ThrowUtils.throwIf(body == null, ErrorCode.OPERATION_ERROR);*/
        return  JSON.parseObject(body);
    }

    // 获取session_key和openid
    public static JSONObject getOpenIdByCode(String appId, String secret, String code) {
        String apiUrl = StrUtil.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code",
                appId, secret, code
        );

        String body = HttpRequest.post(apiUrl).execute().body();
       /* ThrowUtils.throwIf(body == null, ErrorCode.OPERATION_ERROR);*/
        return JSON.parseObject(body);
    }

    //
    public static JSONObject getPhoneByCode(String accessToken, String code) {
        String apiUrl = StrUtil.format(
                "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={}",
                accessToken
        );
        HashMap<String, Object> requestParam = new HashMap<>();
        // 手机号调用凭证
        requestParam.put("code", code);
        String body = HttpRequest.post(apiUrl).body(JSON.toJSONString(requestParam)).execute().body();
        /* ThrowUtils.throwIf(body == null, ErrorCode.OPERATION_ERROR);*/
        return JSON.parseObject(body);
    }
}
